package com.test.map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.test.map.HTTP.OKHttp;
import com.test.map.Users.Client;
import com.test.map.Users.Customer;
import com.test.map.Users.Order_client;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;


public class  CustomerList extends Activity {
    public FormBody body;
    private OKHttp okHttp;
    private ArrayList<String> infoList ;
    public JSONArray list;
    public JSONObject Arrya_Order,Array_Client;
    public App app;
    private List<Customer> mCustomerList;
    private RecyclerView newsTitleRecyclerView;
    ArrayList<Client> clients=new ArrayList<>();
    CustomerAdapter adapter;
    public List<Customer> newlist;

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.customer_frag);
        app=(App) getApplication();
        infoList = getIntent().getStringArrayListExtra("driver");
        newsTitleRecyclerView=(RecyclerView)findViewById(R.id.recycler_view);
        LinearLayoutManager layoutManager=new LinearLayoutManager(this);
        newsTitleRecyclerView.setLayoutManager(layoutManager);

        adapter=new CustomerAdapter(getNews(clients));
        newsTitleRecyclerView.setAdapter(adapter);
        Button button = (Button) findViewById(R.id.work);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCustomerList.clear();
                if(newlist!=null){
                for (int i = 0; i < newlist.size(); i++)
                    mCustomerList.add(newlist.get(i));
                adapter.notifyDataSetChanged();
                }

            }
        });
       //将返回的订单表加入RecyclerView
        Work(Array_Client);

        new Thread(new Runnable(){
            @Override
            public void run() {
                try {


                    do{
                        okHttp.post("http://47.105.179.182:5000/acceptOrder",body);
                        Thread.sleep(2*1000);

                    }while (okHttp.s.equals(""));

                    String a=okHttp.s;
                    Array_Client=new JSONObject(a);
                    clients=new Client().parsing(Array_Client.getJSONArray("result"));

                    newlist= getNews(clients);

                } catch (InterruptedException e) {

                } catch (JSONException e) {

                }
            }

        }).start();


    }

    private List<Customer> getNews(ArrayList<Client> clients){
        List<Customer> newsList=new ArrayList<>();
        if (clients.isEmpty())return newsList;
        for(int i=0;i<clients.size();i++){
            String customer = "customer" + (i%4+1);
            Context ctx=getBaseContext();
            int resId = getResources().getIdentifier(customer, "drawable" , ctx.getPackageName());
            Customer news=new Customer(clients.get(i).getName()+"    费用："+clients.get(i).getPrice(), resId,
                    "电话"+clients.get(i).getPhone()+"\n目的地："+clients.get(i).getPlace(),
                    "距离我："+ Integer.valueOf(clients.get(i).getDistance())/1000+"km","所在地:\n"+clients.get(i).getClient_place());
            newsList.add(news);
        }
        return newsList;
    }
    public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder> {



         class ViewHolder extends RecyclerView.ViewHolder {
            ImageView CustomerImage;
            TextView CustomerName;
            TextView CustomerPhone;
            TextView CustomerDistance;
            TextView CustomerLocation;

             public int getId() {
                 return id;
             }

             int id;
            public ViewHolder(View view) {
                super(view);
                CustomerImage = (ImageView) view.findViewById(R.id.customer_image);
                CustomerName = (TextView) view.findViewById(R.id.customer_name);
                CustomerPhone = (TextView) view.findViewById(R.id.customer_phone);
                CustomerDistance = (TextView) view.findViewById(R.id.customer_distance);
                CustomerLocation = (TextView) view.findViewById(R.id.customer_location);
            }

        }

        public CustomerAdapter(List<Customer> CustomerList) {
            mCustomerList = CustomerList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
            final ViewHolder holder = new ViewHolder(view);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    final ProgressDialog progressDialog=new ProgressDialog(CustomerList.this);
                    progressDialog.setTitle("正在提交请求");
                    progressDialog.setCancelable(true);
                    progressDialog.show();
                    Choose();
                    new Thread(new Runnable(){
                        @Override
                        public void run() {
                            try {
                                okHttp.post("http://47.105.179.182:5000/takeOrder/"+clients.get(holder.getId()).getOrder_id(),body);

                                Thread.sleep(2*1000);
                                String a=okHttp.s;
                                Arrya_Order=new JSONObject(a);
                                Order_client order=new Order_client().parsing(Arrya_Order);
                                System.out.print(order.getDestName());
                                progressDialog.dismiss();

                                ArrayList<String> info = new ArrayList<String>();

                                info.add(order.getDestLatitude());
                                info.add(order.getDestLongitude());
                                info.add(order.getDestName());
                                app.des=order.getDestName();
                                //Thread.sleep(3*1000);Toast.makeText(CustomerList.this, "成功接待单，即将前往："+order.getDestName(), Toast.LENGTH_SHORT).show();//成功了弹出登陆成功
                                Intent intent=new Intent(CustomerList.this,DriverMap.class);
                                intent.putStringArrayListExtra("order", info);
                                startActivity(intent);

                            } catch (InterruptedException e) {

                            } catch (JSONException e) {

                            }
                        }

                    }).start();




                }
            });
            return holder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Customer Customer = mCustomerList.get(position);
            holder.CustomerImage.setImageResource(Customer.getImageId());
            holder.CustomerName.setText(Customer.getName());
            holder.CustomerPhone.setText(Customer.getPhoneid());
            holder.CustomerDistance.setText(Customer.getDistance());
            holder.CustomerLocation.setText(Customer.getLocation());
            holder.id=position;
        }

        @Override
        public int getItemCount() {
            return mCustomerList.size();
        }
    }
    public void Work(JSONObject Array_Client)  {
        long currentTime = System.currentTimeMillis();
        String.valueOf(System.currentTimeMillis());
        String timeNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTime);
        body = new FormBody.Builder()
                .add("uid",app.getUid())
                .add("longitude", infoList.get(1))
                .add("latitude", infoList.get(0))
                .build();
        okHttp= new OKHttp();

    }

    public void Choose()  {

        App app=(App) getApplication();
        app.getUid();

        body = new FormBody.Builder()
                .add("uid",app.getUid())
                .add("longitude", infoList.get(1))
                .add("latitude", infoList.get(0))
                .build();
        okHttp= new OKHttp();

    }


}